from time import sleep
from tkinter import ttk, Entry, scrolledtext
from tkinter import *
from requests import get, post, RequestException, HTTPError, ConnectionError, Timeout
from ModeType.Base import BaseOutput

def make_request(url, method, timeout=10):
    response = None
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit"
            "/537.36 (KHTML, like Gecko) "
            "Chrome/110.0.0.0 Safari/537.36"}
    try:
        if method == 'get':
            response = get(url, timeout=timeout, headers=headers)
        elif method == 'post':
            response = post(url, timeout=timeout, headers=headers)
        # 检查响应状态码
        response.raise_for_status()  # 如果状态码不是 200，将抛出 HTTPError 异常
        return response
    except HTTPError as http_err:
        return f"HTTP error occurred: {http_err}"  # 通常是 4xx 或 5xx 错误
    except ConnectionError as conn_err:
        return f"Error connecting: {conn_err}"  # 网络连接问题
    except Timeout as timeout_err:
        return f"The request timed out: {timeout_err}"  # 请求超时
    except RequestException as req_err:
        return f"An error occurred: {req_err}"  # 其他请求错误
    except Exception as e:
        return f"An unexpected error occurred: {e}"  # 捕获其他未处理的异常

# 接口式输出
class ApiResult(BaseOutput):
    def createConfig(self, root):
        self.commonConfig(root)
        box = ttk.LabelFrame(root, text='api 输出配置')
        box.pack(padx=10, pady=10)

        row = 0
        ttk.Label(box, text='接口地址').grid(row=row, column=0)
        self.req_url = scrolledtext.ScrolledText(box, height=6)
        self.req_url.insert(INSERT, 'https://unpkg.com/china-division@2.7.0/dist/provinces.json')
        self.req_url.grid(row=row, column=1, pady=4, sticky=W+E+N+S)

        row += 1
        ttk.Label(box, text='请求方式').grid(row=row, column=0)
        self.method = ttk.Combobox(box, values=['get', 'post'])
        self.method.current(0)
        self.method.grid(row=row, column=1, pady=4, sticky=W+E+N+S)

        row += 1
        ttk.Label(box, text='返回结果展示').grid(row=row, column=0)
        self.resData = scrolledtext.ScrolledText(box, height=3)
        self.resData.grid(row=row, column=1, pady=4, sticky=W+E+N+S)

        row += 1
        ttk.Label(box, text='返回结果字段').grid(row=row, column=0)
        self.resKey = Entry(box)
        self.resKey.grid(row=row, column=1, pady=4, sticky=W+E+N+S)

        row += 1
        ttk.Label(box, text='每条数据文案字段').grid(row=row, column=0)
        self.itemKey = Entry(box)
        self.itemKey.insert(0, 'name')
        self.itemKey.grid(row=row, column=1, pady=4, sticky=W+E+N+S)

        return box

    def run(self):
        url = self.req_url.get(1.0, END).strip('\n')
        dataK = self.resKey.get()
        itemK = self.itemKey.get()
        method = self.method.get()

        res = make_request(url=url, method=method)
        self.resData.delete(1.0, END)
        if isinstance(res, str):
           print(res)
           self.resData.insert(INSERT, res)
           print('接口返回失败，不在执行')
           return

        self.resData.insert(INSERT, res.text)
        data = res.json()
        listData = data
        if dataK:
            listData = data[dataK]

        speed = self.get_speed()
        for i in range(len(listData)):
            if self.stop:
                break
            item = listData[i]
            if self.itemKey:
                item = item[itemK]
            self.keyResultContent(item)
            sleep(speed)
